<template>
  <div class="app-container">
    <!-- 顶部搜索和操作区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="queryParams.teamName" placeholder="搜索班组名称" clearable @clear="handleQuery"
            @keyup.enter="handleQuery" />
        </el-col>
        <el-col :span="4">
          <el-select v-model="queryParams.exp" placeholder="经验等级" clearable>
            <el-option v-for="item in experienceOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="queryParams.timeFrame" placeholder="工作时段" clearable>
            <el-option v-for="item in timeFrameOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="4" class="text-left">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 班组列表表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog">
        <el-icon>
          <Plus />
        </el-icon>新增班组
      </el-button>
      <el-table :data="teamList" border style="width: 100%" v-loading="loading" class="mt-2"
        @selection-change="handleSelectionChange" :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="teamName" label="班组名称" />
        <el-table-column prop="teamLeaderName" label="班组长" />
        <el-table-column prop="teamMemberCount" label="成员数量" />
        <el-table-column label="经验等级">
          <template #default="{ row }">
            <el-tag :type="getExperienceTag(row.exp)">
              {{ getExperienceLabel(row.exp) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="工作时段">
          <template #default="{ row }">
            {{ getTimeFrameLabel(row.timeFrame) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showDetailDialog(row)">详情</el-button>
            <el-button size="small" type="primary" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteTeamVue(row.teamsAndGroupsId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 班组详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`班组详情 - ${detailDialog.data?.teamName || ''}`" width="70%"
      :close-on-click-modal="false">
      <el-descriptions :column="2" border v-if="detailDialog.data">
        <el-descriptions-item label="班组名称">{{ detailDialog.data.teamName }}</el-descriptions-item>
        <el-descriptions-item label="班组长">{{ detailDialog.data.teamLeaderName }}</el-descriptions-item>
        <el-descriptions-item label="成员数量">{{ detailDialog.data.teamMemberCount }}</el-descriptions-item>
        <el-descriptions-item label="经验等级">
          <el-tag :type="getExperienceTag(detailDialog.data.exp)">
            {{ getExperienceLabel(detailDialog.data.exp) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="工作时段">
          {{ getTimeFrameLabel(detailDialog.data.timeFrame) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 班组成员列表 -->
      <div class="mt-4">
        <div class="flex justify-between items-center mb-2">
          <h3>班组成员</h3>
          <el-button type="primary" size="small" @click="showAddMemberDialog">
            <el-icon>
              <Plus />
            </el-icon>添加成员
          </el-button>
        </div>

        <el-table :data="detailDialog.data?.memberList || []" border>
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column prop="jobNumber" label="工号" align="center" />
          <el-table-column label="职位" align="center">
            <template #default="{ row }">
              <el-tag>{{ ['', '成员', '班长', '调度员'][row.post] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="phoneNumber" label="联系方式" align="center" />
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="removeMember(row.memberId)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑班组对话框 -->
    <el-dialog v-model="teamDialog.visible" :title="teamDialog.title" width="50%" :close-on-click-modal="false">
      <el-form :model="currentTeam" :rules="teamRules" ref="teamFormRef" label-width="100px">
        <el-form-item label="班组名称" prop="teamName">
          <el-input v-model="currentTeam.teamName" placeholder="请输入班组名称" />
        </el-form-item>
        <el-form-item label="班组长" prop="teamLeaderId">
          <el-select v-model="currentTeam.teamLeaderId" placeholder="请选择班组长" style="width: 100%">
            <el-option v-for="member in memberOptions" :key="member.id" :label="member.name" :value="member.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="经验等级" prop="exp">
          <el-select v-model="currentTeam.exp" placeholder="请选择经验等级" style="width: 100%">
            <el-option v-for="item in experienceOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作时段" prop="timeFrame">
          <el-select v-model="currentTeam.timeFrame" placeholder="请选择工作时段" style="width: 100%">
            <el-option v-for="item in timeFrameOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="teamDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加成员对话框 -->
    <el-dialog v-model="memberDialog.visible" title="添加班组成员" width="60%" :close-on-click-modal="false">
      <el-input v-model="memberSearch.keyword" placeholder="搜索成员姓名或工号" clearable class="mb-3" @clear="searchMembers"
        @keyup.enter="searchMembers" />

      <el-table :data="filteredMembers" border style="width: 100%" @selection-change="handleMemberSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="jobNumber" label="工号" align="center" />
        <el-table-column prop="post" label="职位" align="center" />
        <el-table-column prop="phoneNumber" label="联系方式" align="center" />
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="memberDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddMembers">添加</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Refresh } from '@element-plus/icons-vue'
import {
  getTimeFrameList,
  getExperienceList,
  getTeamList,
  getTeamDetail,
  addTeam,
  updateTeam,
  deleteTeam,
  getMemberList,
  addMember,
  exportTeam,
  deleteMember
} from '@/api/dispatch/affair/team_manage'

// 加载状态
const loading = ref(false)
const teamFormRef = ref(null);
// 下拉选项数据
const timeFrameOptions = ref([])
const experienceOptions = ref([])
const memberOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  teamName: '',
  exp: '',
  timeFrame: ''
})

// 班组列表数据
const teamList = ref([])
const total = ref(0)

// 当前操作的班组
const currentTeam = reactive({
  teamsAndGroupsId: '',
  teamName: '',
  teamLeaderId: '',
  exp: '',
  timeFrame: ''
})

// 对话框控制
const detailDialog = reactive({
  visible: false,
  data: null
})

const teamDialog = reactive({
  visible: false,
  title: '新增班组'
})

const memberDialog = reactive({
  visible: false,
  teamId: ''
})

// 成员搜索
const memberSearch = reactive({
  keyword: ''
})

// 选中的成员
const selectedMembers = ref([])

// 选中的班组
const selectedTeams = ref([])

// 表单验证规则
const teamRules = reactive({
  teamName: [
    { required: true, message: '请输入班组名称', trigger: 'blur' }
  ],
  teamLeaderId: [
    { required: true, message: '请选择班组长', trigger: 'change' }
  ],
  exp: [
    { required: true, message: '请选择经验等级', trigger: 'change' }
  ],
  timeFrame: [
    { required: true, message: '请选择工作时段', trigger: 'change' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取时段下拉列表
    const timeFrameRes = await getTimeFrameList()
    timeFrameOptions.value = timeFrameRes.data

    // 获取经验下拉列表
    const expRes = await getExperienceList()
    experienceOptions.value = expRes.data

    // 获取成员列表
    const memberRes = await getMemberList()
    memberOptions.value = memberRes.data

    // 获取班组列表
    await fetchTeamList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取班组列表
const fetchTeamList = async () => {
  try {
    loading.value = true
    const res = await getTeamList(queryParams)
    teamList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取班组列表失败:', error)
    ElMessage.error('获取班组列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchTeamList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.teamName = ''
  queryParams.exp = ''
  queryParams.timeFrame = ''
  handleQuery()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchTeamList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchTeamList()
}

// 显示新增对话框
const showAddDialog = () => {
  teamDialog.title = '新增班组'
  resetCurrentTeam()
  teamDialog.visible = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await getTeamDetail(row.teamsAndGroupsId)
    Object.assign(currentTeam, res.data)
    teamDialog.title = '编辑班组'
    teamDialog.visible = true
  } catch (error) {
    console.error('获取班组详情失败:', error)
    ElMessage.error('获取班组详情失败')
  } finally {
    loading.value = false
  }
}

// 重置当前班组
const resetCurrentTeam = () => {
  currentTeam.teamsAndGroupsId = ''
  currentTeam.teamName = ''
  currentTeam.teamLeaderId = ''
  currentTeam.exp = ''
  currentTeam.timeFrame = ''
}

// 确认保存
const confirmSave = async () => {
  try {
    await teamFormRef.value.validate()

    if (teamDialog.title === '新增班组') {
      await addTeam(currentTeam)
      ElMessage.success('新增班组成功')
    } else {
      await updateTeam(currentTeam)
      ElMessage.success('修改班组成功')
    }

    teamDialog.visible = false
    fetchTeamList()
  } catch (error) {
    console.error('保存班组失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 显示详情对话框
const showDetailDialog = async (row) => {
  try {
    loading.value = true
    const res = await getTeamDetail(row.teamsAndGroupsId)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取班组详情失败:', error)
    ElMessage.error('获取班组详情失败')
  } finally {
    loading.value = false
  }
}

// 显示添加成员对话框
const showAddMemberDialog = () => {
  memberDialog.teamId = detailDialog.data.teamsAndGroupsId
  memberDialog.visible = true
  memberSearch.keyword = ''
  selectedMembers.value = []
}

// 处理成员选择
const handleMemberSelectionChange = (selection) => {
  console.log(selection);

  selectedMembers.value = selection.map(item => item.memberId)
}

// 搜索成员
const searchMembers = () => {
  // 搜索逻辑已在计算属性中实现
}

// 过滤后的成员列表
const filteredMembers = computed(() => {
  if (!memberSearch.keyword) return memberOptions.value

  const keyword = memberSearch.keyword.toLowerCase()
  return memberOptions.value.filter(member =>
    member.name.toLowerCase().includes(keyword) ||
    member.jobNumber.toLowerCase().includes(keyword)
  )
})

// 确认添加成员
const confirmAddMembers = async () => {
  if (selectedMembers.value.length === 0) {
    ElMessage.warning('请至少选择一名成员')
    return
  }
  console.log(selectedMembers.value);

  try {
    loading.value = true
    await addMember({
      teamsAndGroupsId: memberDialog.teamId,
      memberId: selectedMembers.value.join(',')
    })
    ElMessage.success('添加成员成功')
    memberDialog.visible = false

    // 刷新详情数据
    const res = await getTeamDetail(memberDialog.teamId)
    detailDialog.data = res.data
  } catch (error) {
    console.error('添加成员失败:', error)
    ElMessage.error('添加成员失败')
  } finally {
    loading.value = false
  }
}

// 移除成员
const removeMember = (memberId) => {
  ElMessageBox.confirm('确认移除该成员吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里需要调用移除成员的API
      
      await deleteMember({
        teamsAndGroupsId: detailDialog.data.teamsAndGroupsId,
        memberId: memberId
      })
      ElMessage.success('移除成员成功')

      // 刷新详情数据
      const res = await getTeamDetail(detailDialog.data.teamsAndGroupsId)
      detailDialog.data = res.data
    } catch (error) {
      console.error('移除成员失败:', error)
      ElMessage.error('移除成员失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 删除班组
const deleteTeamVue = (id) => {
  ElMessageBox.confirm('确认删除该班组吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTeam(id)
      ElMessage.success('删除成功')
      fetchTeamList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除
const batchDelete = () => {
  if (selectedTeams.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm('确认删除选中的班组吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTeam(selectedTeams.value.join(','))
      ElMessage.success('删除成功')
      fetchTeamList()
      selectedTeams.value = []
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 处理表格选择
const handleSelectionChange = (selection) => {
  selectedTeams.value = selection.map(item => item.teamsAndGroupsId)
}

// 导出数据
const handleExport = async () => {
  try {
    loading.value = true
    const res = await exportTeam(queryParams)
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '班组列表.xlsx'
    link.click()
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchTeamList()
  ElMessage.success('刷新成功')
}

// 获取经验等级标签
const getExperienceTag = (exp) => {
  switch (exp) {
    case '0': return 'primary'
    case '1': return 'warning'
    case '2': return 'success'
    default: return ''
  }
}

// 获取经验等级文本
const getExperienceLabel = (exp) => {
  const item = experienceOptions.value.find(item => item.id == exp)
  return item ? item.name : exp
}

// 获取工作时段文本
const getTimeFrameLabel = (timeFrame) => {
  const item = timeFrameOptions.value.find(item => item.id == timeFrame)
  return item ? item.name : timeFrame
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.text-right {
  text-align: right;
}

.mt-1 {
  margin-top: 10px;
}

.mt-2 {
  margin-top: 20px;
}

.mt-4 {
  margin-top: 40px;
}

.mb-3 {
  margin-bottom: 30px;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}
</style>